import * as Cesium from "cesium";
import { createApp, h, ref } from "vue";
import Popup from "./Popupneibo.vue";

export default class TerrainDialog {
  constructor(opts) {
    const { viewer, position, ...rest } = opts;
    this.viewer = viewer;
    this.position = position._value;
    
    // 创建响应式数据引用
    this.gridDataRef = ref(opts.gridData || null);
    this.roadPathRef = ref(opts.roadPath || []);
    
    const { vmInstance } = createDialog({
      ...rest,
      gridData: this.gridDataRef,
      roadPath: this.roadPathRef,
      closeEvent: this.windowClose.bind(this),
    });
    
    if (this.vmInstance) {
      this.windowClose.bind(this);
    } else {
      this.vmInstance = vmInstance;
    }
    viewer.cesiumWidget.container.appendChild(vmInstance.$el);
    this.addPostRender();
  }
  // 更新地形数据
  updateGridData(newData) {
    this.gridDataRef.value = newData;
  }

  // 更新公路路径
  updateRoadPath(newPath) {
    this.roadPathRef.value = newPath;
  }

  addPostRender() {
    this.viewer.scene.postRender.addEventListener(this.postRender, this);
  }

  postRender() {
    if (!this.vmInstance?.$el || !this.vmInstance.$el.style) return;
    
    // 固定到右上角位置
    this.vmInstance.$el.style.position = 'fixed';
    this.vmInstance.$el.style.top = '50%';  // 距离顶部20px
    this.vmInstance.$el.style.right = 'auto'; // 距离右侧20px
    this.vmInstance.$el.style.bottom = 'auto'; // 清除之前的bottom设置
    this.vmInstance.$el.style.left = '16%';   // 清除之前的left设置
    
    // 根据相机距离控制显示/隐藏
    const camerPosition = this.viewer.camera.position;
    let height = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(
      camerPosition
    ).height;
    height += this.viewer.scene.globe.ellipsoid.maximumRadius;
    
    if (
      !(Cesium.Cartesian3.distance(camerPosition, this.position) > height) &&
      this.viewer.camera.positionCartographic.height < 50000000
    ) {
      this.vmInstance.$el.style.display = "block";
    } else {
      this.vmInstance.$el.style.display = "none";
    }
}

  // postRender() {
  //   if (!this.vmInstance?.$el || !this.vmInstance.$el.style) return;
    
  //   const canvasHeight = this.viewer.scene.canvas.height;
  //   const windowPosition = new Cesium.Cartesian2();
    
  //   Cesium.SceneTransforms.worldToWindowCoordinates(
  //     this.viewer.scene,
  //     this.position,
  //     windowPosition
  //   );

  //   // 调整弹窗位置
  //   this.vmInstance.$el.style.bottom = 
  //     canvasHeight - windowPosition.y + 260 + "px";
    
  //   const elWidth = this.vmInstance.$el.offsetWidth;
  //   this.vmInstance.$el.style.left = 
  //     windowPosition.x - elWidth / 2 + 110 + "px";

  //   // 根据相机距离控制显示/隐藏
  //   const camerPosition = this.viewer.camera.position;
  //   let height = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(
  //     camerPosition
  //   ).height;
  //   height += this.viewer.scene.globe.ellipsoid.maximumRadius;
    
  //   if (
  //     !(Cesium.Cartesian3.distance(camerPosition, this.position) > height) &&
  //     this.viewer.camera.positionCartographic.height < 50000000
  //   ) {
  //     this.vmInstance.$el.style.display = "block";
  //   } else {
  //     this.vmInstance.$el.style.display = "none";
  //   }
  // }

  // 在 Dialog 类或相关管理类中添加
  windowClose() {
    try {
      if (this.vmInstance) {
        // 先移除事件监听
        this.viewer.scene.postRender.removeEventListener(this.postRender, this);
        
        // 强制释放WebGL资源
        const chartContainer = this.vmInstance.$el.querySelector("#echartsContainer");
        if (chartContainer) {
          const canvas = chartContainer.querySelector("canvas");
          if (canvas) {
            const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
            if (gl) {
              const loseContext = gl.getExtension("WEBGL_lose_context");
              if (loseContext) loseContext.loseContext();
            }
          }
        }
  
        // 延迟移除DOM元素
        setTimeout(() => {
          if (this.vmInstance.$el && this.vmInstance.$el.parentNode) {
            this.vmInstance.$el.parentNode.removeChild(this.vmInstance.$el);
          }
          this.vmInstance = null;
        }, 0);
      }
    } catch (e) {
      console.error("关闭弹窗时出错:", e);
    }
  }
}
let parentNode = null;
const createDialog=(opts)=> {
  if (parentNode) {
    // document.body.removeChild(parentNode);
    parentNode = null;
  }
  const app = createApp({
    render() {
      return h(
        Popup,
        {
          ...opts,
          gridData: opts.gridData,
          roadPath: opts.roadPath
        },
        {
          title: () => opts.slotTitle,
          content: () => opts.slotContent,
        }
      );
    },
  });

  parentNode = document.createElement("div");
  const instance = app.mount(parentNode);
  document.body.appendChild(parentNode);

  return { vmInstance: instance };
}